import Adafruit_DHT
import time
import paho.mqtt.client as mqtt
import json

# MQTT服务器设置
MQTT_BROKER = "broker.emqx.io"  # 例如: "broker.hivemq.com"
MQTT_PORT = 1883  # MQTT默认端口
MQTT_TOPIC = "watering/Air"  # 你要发布的MQTT主题
MQTT_CLIENT_ID = "mqttx_c7c21bb7"  # MQTT客户端ID

# Set sensor type and GPIO
sensor = Adafruit_DHT.DHT11
gpio = 23

# MQTT回调函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    # 订阅主题（如果需要的话）
    # client.subscribe("your/topic")

# MQTT发布函数
def publish_data(client, humidity, temperature):
    data = {
        "AirMoisture":humidity,
        "Temperature":temperature
    }
    payload = json.dumps(data)
    client.publish(MQTT_TOPIC, payload)

# MQTT客户端
client = mqtt.Client(MQTT_CLIENT_ID)
client.on_connect = on_connect

# 连接到MQTT服务器
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 保持MQTT连接
client.loop_start()

try:
    while True:
        time.sleep(5)
        humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
        if humidity is not None and temperature is not None:
            print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
            publish_data(client, humidity, temperature)
        else:
            print('Failed to get reading. Try again!')
finally:
    # 清理和断开MQTT连接
    client.loop_stop()
    client.disconnect()
